package com.springboot.middleware.middleware_redisson.server.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {
    @Value("${mq.redisson.dead.queue.name}")
    private String deadQueueName;
    @Value("${mq.redisson.dead.exchange.name}")
    private String deadExchangeName;
    @Value("${mq.redisson.dead.routing.key}")
    private String deadRoutingKey;
    @Value("${mq.redisson.dead.basic.exchange.name}")
    private String basicExchangeName;
    @Value("${mq.redisson.dead.basic.routing.key}")
    private String basicRoutingKey;
    @Value("${mq.redisson.real.queue.name}")
    private String realQueueName;

    //创建死信队列, 绑定死信交换机和死信路由器
    @Bean
    public Queue redissonDeadQueue() {
        Map<String, Object> argsMap = new HashMap<>();
        argsMap.put("x-dead-letter-exchange", deadExchangeName);
        argsMap.put("x-dead-letter-routing-key", deadRoutingKey);
        return new Queue(deadQueueName, true, false, false, argsMap);
    }

    //创建基本路由器
    @Bean
    public TopicExchange redissonBasicExchange() {
        return new TopicExchange(basicExchangeName, true, false);
    }

    //绑定死信队列和基本路由器
    @Bean
    public Binding redissonDeadQueueBinding() {
        return BindingBuilder.bind(redissonDeadQueue()).to(redissonBasicExchange()).with(basicRoutingKey);
    }

    //创建死信交换机
    @Bean
    public TopicExchange redissonDeadExchange() {
        return new TopicExchange(deadExchangeName, true, false);
    }

    //创建真正队列 - 面向消费者
    @Bean
    public Queue redissonRealQueue() {
        return new Queue(realQueueName, true);
    }

    //绑定死信交换机和真正队列
    @Bean
    public Binding redissonRealQueueBinding() {
        return BindingBuilder.bind(redissonRealQueue()).to(redissonDeadExchange()).with(deadRoutingKey);
    }

    /**
     * 添加这个类进行序列化解析
     * 会自动识别
     * @param objectMapper json序列化实现类
     * @return mq消息序列化工具
     */
    @Bean
    public MessageConverter jsonMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }
}
